<template>
  <div class="home">
    <el-row :gutter="24" justify="center">
      <el-col v-if="!statList.length">敬请期待!</el-col>
      <el-col v-else :xs="24" :sm="6" :md="6" :lg="6" :xl="6"
              v-for="(item,index) in statList" :key="index">
        <div class="grid-content">
          <div class="goods-img-box">
            <el-image :src="showImg" class="goods-img"/>
          </div>
          <div class="grid-content-p">
            <p>{{ item.goodsName }}</p>
            <p class="goods-price">
              <span>
                单价：{{ item.goodsPrice }} 元
                <el-button type="primary" :icon="ShoppingCartFull" size="small" plain
                           style="margin-left: 10px" @click="goBuy(item)"/>
              </span>
              <span class="goods-num">库存：{{ item.goodsCount }}</span>
            </p>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="确定订单" v-model="dialogPay" width="720" :before-close="rowClose" :show-close="false">
      <div class="pay-box">
        <div class="pay-info">
          <p>订单信息</p>
          <el-form :model="payVo" :rules="formRules" ref="loginFormRef" label-position="right">
            <el-form-item label="物品名称：">
              {{ payVo.goodsName }}
            </el-form-item>
            <el-form-item label="单价：">
              {{ payVo.goodsPrice }} 元
            </el-form-item>
            <el-form-item label="库存：">
              {{ payVo.goodsCount }}
            </el-form-item>
            <el-form-item label="订单金额：">
              {{ payVo.payAmt }} 元
            </el-form-item>
            <el-form-item label="购买数量：" prop="goodsNum">
              <el-input-number size="small"
                               v-model="payVo.goodsNum" :min="1" @change="monitorNum"/>
            </el-form-item>
            <el-form-item label="支付方式：" prop="payType">
              <el-select v-model="payVo.payType" placeholder="选择支付方式" clearable size="small" @change="changeType">
                <el-option label="微信" value="wxpay"/>
                <el-option label="支付宝" value="alipay"/>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="pay-code" v-if="showCOde">
          <p>扫码支付</p>
          <el-image style="width: 100px; height: 100px"
                    :src="urlPay" fit="cover"/>
          <p>提示：请使用扫码支付，支付成功后请及时联系客服确认订单</p>
          <p>如果微信无法支付请切换支付宝</p>
        </div>
        <div class="pay-code" v-else>
          <el-button type="primary" @click="goToCode">去支付</el-button>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogPay = false">取消支付</el-button>
          <el-button type="primary" @click="checkIfUserHasPaid(payVo.orderNo)">已支付</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="确定订单" v-model="dialogPayModel" width="360" :before-close="rowClose" :show-close="false">
      <div class="pay-box">
        <div class="pay-info">
          <p>订单信息</p>
          <el-form :model="payVo" :rules="formRules" ref="loginFormRef" label-position="right">
            <el-form-item label="物品名称：">
              {{ payVo.goodsName }}
            </el-form-item>
            <el-form-item label="单价：">
              {{ payVo.goodsPrice }} 元
            </el-form-item>
            <el-form-item label="库存：">
              {{ payVo.goodsCount }}
            </el-form-item>
            <el-form-item label="订单金额：">
              {{ payVo.payAmt }} 元
            </el-form-item>
            <el-form-item label="购买数量：" prop="goodsNum">
              <el-input-number size="small"
                               v-model="payVo.goodsNum" :min="1" @change="monitorNum"/>
            </el-form-item>
            <el-form-item label="支付方式：" prop="payType">
              <el-select v-model="payVo.payType" placeholder="选择支付方式" clearable size="small" @change="changeType">
                <el-option label="微信" value="wxpay"/>
                <el-option label="支付宝" value="alipay"/>
              </el-select>
            </el-form-item>
            <p>提示：支付成功后请及时联系客服确认订单</p>
            <p>如果微信无法支付请切换支付宝</p>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogPayModel = false">取消支付</el-button>
          <el-button type="primary" @click="goModelBuy">确定支付</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import api from "@/api";
import store from '@/store/index'
import {generateUniqueRandomNumbers} from "@/utils/globalVariables";
import {ref, onMounted, watch} from "vue"
import {ShoppingCartFull} from '@element-plus/icons-vue'
import {useRouter} from 'vue-router'
import {ElMessage} from "element-plus"

const router = useRouter()

onMounted(() => {
  // 判断是否为PC端
  const isMobile = /Mobi|Android/i.test(navigator.userAgent);
  if (isMobile) {
    isPhone.value = true
  }
  fetchGoodsList()
})

const showCOde = ref(false)
//生成支付
const goToCode = async() => {
  //生成唯一订单号并检查其唯一性
  await checkPaymentStatus()
  if (payVo.value.orderNo) {
    getPayCode(payVo);
  }
}
const changeType = async () => {
  showCOde.value = false
  // await checkPaymentStatus()
  // if (payVo.value.orderNo) {
  //   getPayCode(payVo);
  // }
}
const isPhone = ref(false)
const dialogPay = ref(false)
const dialogPayModel = ref(false)
const payCode = ref('')
const urlPayModel = ref('')
const goModelBuy = () => {
  goToCode()
}

//单笔限购数量
const monitorNum = () => {
  showCOde.value = false
  //数量不能超过库存
  if (payVo.value.goodsNum > payVo.value.goodsCount) {
    ElMessage.error('购买数量不能超过库存')
    payVo.value.goodsNum = 1
    payVo.value.payAmt = payVo.value.goodsPrice;
    return
  }
  //如果数量乘以价格 总价大于1000 就提示
  payVo.value.payAmt = Number(payVo.value.goodsPrice) * Number(payVo.value.goodsNum)
  if (Number(payVo.value.payAmt) > 1000) {
    ElMessage.error('单笔限购1000元')
    payVo.value.goodsNum = 1
    payVo.value.payAmt = payVo.value.goodsPrice;
  }
  // getPayCode(payVo);
}
const rowClose = () => {
  checkIfUserHasPaid(payVo.value.orderNo)
}
const payVo = ref({
  payAmt: '',
  goodsId: '',
  goodsName: '',
  goodsPrice: '',
  goodsCount: '',
  goodsNum: '1',
  payType: 'alipay',
  orderNo: '',
  clientip: '',
  userId: '',
})
const goBuy = async (item) => {
  if (!item.goodsCount > 0) {
    ElMessage.error('库存不足')
    return
  }
  payVo.value.goodsCount = item.goodsCount
  payVo.value.goodsName = item.goodsName
  payVo.value.goodsPrice = item.goodsPrice
  payVo.value.payAmt = Number(item.goodsPrice) * Number(payVo.value.goodsNum)
  if (isPhone.value) {
    dialogPayModel.value = true
    return
  }
  dialogPay.value = true;
}
let maxRetries = 5; // 最大重试次数

//检查订单号是否重复
const checkPaymentStatus = async () => {
  let orderNo = generateUniqueRandomNumbers();
  let retries = 0;
  let isUnique = false;

  while (!isUnique && retries < maxRetries) {
    try {
      const response = await api.checkOrderNo(orderNo);
      if (response && (response.status === 401 || response.code === 1)) {
        // 如果订单号不唯一，重新生成
        orderNo = generateUniqueRandomNumbers();
        retries++;
      } else {
        isUnique = true;
      }
    } catch (e) {
      console.error('Error checking order number uniqueness:', e);
      // 出现错误时，增加重试计数
      retries++;
      if (retries >= maxRetries) {
        // 达到最大重试次数，停止尝试
        alert('系统错误，请稍后再试。');
        return;
      }
      // 可选：在重试前等待一段时间，避免连续请求
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }

  if (isUnique) {
    // 设置最终确定的唯一订单号
    payVo.value.orderNo = orderNo;
  } else {
    // 如果达到最大重试次数仍未找到唯一订单号，提示用户
    alert('无法生成唯一订单号，请稍后再试。');
  }
}
const showPayCode = () => {
  getPayCode(payVo.value);
}
const urlPay = ref('')
const getPayCode = async () => {
  try {
    payVo.value.userId = store.state.userInfos.userId
    const response = await api.getPayCode(payVo.value)
    if (response) {
      if (response.count === 3) {
        ElMessage.error(response.message)
        return
      }
      if (response.status === 401 || response.code === 1) {
        ElMessage.error('业务繁忙，请稍后再试！')
        return
      } else {
        urlPay.value = response.message
        urlPayModel.value = response.obj
        if (isPhone.value){
          if (urlPayModel.value) {
            // window.open(urlPayModel.value, '_blank');
            location.href = urlPayModel.value;
            dialogPayModel.value = false
          }
        }else {
          showCOde.value = true
        }
      }
    }
  } catch (e) {
    console.log(e)
  }
}
// 定义支付状态
const isPaid = ref(false);

const checkIfUserHasPaid = async (orderNo) => {
  try {
    const response = await api.checkPay(orderNo); // 假设此函数查询支付状态
    if (response) {
      if (response.status === 401 || response.code === 1) {
        ElMessage.error('业务繁忙，请稍后再查看订单信息！')
        return
      } else {
        if (response.message === '1') {
          ElMessage.success("支付成功，请前往个人中心查看卡密信息！如有问题请联系客服！")
          dialogPay.value = false
          payVo.value.payAmt = ''
          payVo.value.goodsId = ''
          payVo.value.goodsName = ''
          payVo.value.goodsPrice = ''
          payVo.value.goodsCount = ''
          payVo.value.goodsNum = ''
          payVo.value.payType = 'wxpay'
          payVo.value.orderNo = ''
          payVo.value.clientip = ''
        } else {
          ElMessage.error("支付失败，请先支付！")
        }
      }
    }
  } catch (error) {
    console.error('检查支付状态失败', error);
  }
};

const showImg = ref(require('../assets/f5ef6c128eaabae5178e608be6103796bc1fdce66b3df-aTb3ki.png'))
let statList = ref([])
const fetchGoodsList = async () => {
  try {
    const response = await api.getGoodsList()
    if (response) {
      if (response.status === 401 || response.code === 1) {
        ElMessage.error('暂无物品，敬请期待')
      } else {
        statList.value = response.stat
      }
    }
  } catch (error) {
    console.error(error)
  }
}

const formRules = {
  goodsNum: [
    {required: true, message: '请输入物品数量', trigger: 'change'},
  ],
  payType: [
    {required: true, message: '请选择支付方式', trigger: 'blur'},
  ],
}
// TODO 表单整体校验 + 登录
const loginFormRef = ref(null)
</script>

<style lang="less" scoped>
@import url(../css/home);

.pay-box {
  display: flex;
  box-shadow: 0 0 10 rgb(107 106 106 / 24%);
  padding: 10px;
  margin: 10px;

  .pay-info {
    border-right: 1px solid #909399;
    width: 50%;
  }

  .pay-code {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 50%;
  }
}

/deep/ .el-icon {
  font-size: large;
}

/deep/ .el-form-item {
  margin-bottom: 0;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  border-radius: 4px;
  margin-top: 25px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  box-shadow: 0px 0px 8px rgb(0 0 0 / 24%);

  .goods-img-box {
    padding-top: 10px;
    background: rgb(35 48 51 / 13%);
  }

  .goods-img {
    width: 35%;
    height: auto;
  }

  .grid-content-p {
    text-align: left;
    padding: 0 5%;
    padding-bottom: 10px;
    background: #ffffff;

    p {
      color: #1577ea;
      line-height: 1;
      font-weight: bold;
    }

    .goods-price {
      font-weight: normal;
      color: #efa12a;
      display: flex;
      justify-content: space-between;
      font-size: 15px;
      align-items: center;

      .goods-num {
        color: #585554;
        font-size: 14px;
      }
    }
  }
}
</style>
